package com.nbcio.modules.estar.receipt.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nbcio.modules.erp.sale.entity.ErpSaleOut;
import com.nbcio.modules.erp.sale.entity.ErpSaleOutDetail;
import com.nbcio.modules.erp.sale.service.IErpSaleOutService;
import com.nbcio.modules.estar.cesorder.entity.CesOrderCustomer;
import com.nbcio.modules.estar.cesorder.entity.CesOrderGoods;
import com.nbcio.modules.estar.cesorder.service.ICesOrderCustomerService;
import com.nbcio.modules.estar.cesorder.service.ICesOrderGoodsService;
import com.nbcio.modules.estar.delivery.entity.ErpDelivery;
import com.nbcio.modules.estar.delivery.entity.ErpDeliveryB;
import com.nbcio.modules.estar.delivery.service.IErpDeliveryService;
import com.nbcio.modules.estar.receipt.entity.ErpReceipt;
import com.nbcio.modules.estar.receipt.entity.ErpReceiptDetail;
import com.nbcio.modules.estar.receipt.mapper.ErpReceiptDetailMapper;
import com.nbcio.modules.estar.receipt.mapper.ErpReceiptMapper;
import com.nbcio.modules.estar.receipt.service.IErpReceiptService;
import com.nbcio.modules.flowable.apithird.business.service.IFlowMyBusinessService;
import com.nbcio.modules.flowable.apithird.entity.ActStatus;
import com.nbcio.modules.flowable.apithird.service.FlowCallBackServiceI;
import com.nbcio.modules.flowable.apithird.service.FlowCommonService;
import com.nbcio.modules.flowable.apithird.business.entity.FlowMyBusiness;
import com.nbcio.modules.flowable.utils.StatusEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 收款单主表
 * @Author: nbacheng
 * @Date:   2024-03-19
 * @Version: V1.0
 */
@Service("erpReceiptService")
public class ErpReceiptServiceImpl extends ServiceImpl<ErpReceiptMapper, ErpReceipt> implements IErpReceiptService , FlowCallBackServiceI{



    @Autowired
    FlowCommonService flowCommonService;
	@Autowired
	private ErpReceiptMapper erpReceiptMapper;
	@Autowired
	private ErpReceiptDetailMapper erpReceiptDetailMapper;

	@Autowired
	private IFlowMyBusinessService flowMyBusinessService;


	@Override
	@Transactional
	public void saveMain(ErpReceipt erpReceipt, List<ErpReceiptDetail> erpReceiptDetailList) {
		erpReceiptMapper.insert(erpReceipt);
		if(erpReceiptDetailList!=null && erpReceiptDetailList.size()>0) {
			for(ErpReceiptDetail entity:erpReceiptDetailList) {
				//外键设置
				entity.setReceiptId(erpReceipt.getId());
				erpReceiptDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(ErpReceipt erpReceipt,List<ErpReceiptDetail> erpReceiptDetailList) {
		erpReceiptMapper.updateById(erpReceipt);

		//1.先删除子表数据
		erpReceiptDetailMapper.deleteByMainId(erpReceipt.getId());

		//2.子表数据重新插入
		if(erpReceiptDetailList!=null && erpReceiptDetailList.size()>0) {
			for(ErpReceiptDetail entity:erpReceiptDetailList) {
				//外键设置
				entity.setReceiptId(erpReceipt.getId());
				erpReceiptDetailMapper.insert(entity);
			}
		}
	}


	@Override
	@Transactional
	public void delMain(String id) {
		erpReceiptDetailMapper.deleteByMainId(id);
		erpReceiptMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			erpReceiptDetailMapper.deleteByMainId(id.toString());
			erpReceiptMapper.deleteById(id);
		}
	}
    @Override
    public boolean removeById(Serializable id) {
        /**删除数据，移除流程关联信息**/
        flowCommonService.delActBusiness(id.toString());
        return super.removeById(id);
    }
    /**
     * 流程处理完成后的回调
     * @param business 里面包含流程运行的现状信息，业务层可根据其信息判断，书写增强业务逻辑的代码，<br/>
     *                 1、比如将其中关键信息存入业务表，即可单表业务操作,否则需要关联flow_my_business表获取流程信息<br/>
     *                 2、比如在流程进行到某个节点时(business.taskId)，需要特别进行某些业务逻辑操作等等<br/>
     */
	@Autowired
	ICesOrderGoodsService cesOrderGoodsService;
	@Autowired
	ICesOrderCustomerService cesOrderCustomerService;
	@Autowired
	IErpDeliveryService iErpDeliveryService;

      @Override
      public void afterFlowHandle(FlowMyBusiness business) {

           business.getTaskNameId();//接下来审批的节点
           business.getValues();//前端传进来的参数
           business.getActStatus();//流程状态 ActStatus.java
           //....其他
           ErpReceipt   erpReceipt= this.getById(business.getDataId());
		   if (business.getActStatus().equals(ActStatus.reject) || business.getActStatus().equals(ActStatus.recall)) {
			   erpReceipt.setActstatus(StatusEnum.getEnumKey(ActStatus.start));
			   //删除自定义业务
			   flowMyBusinessService.removeById(business.getId());
		   }else {
			   erpReceipt.setActstatus(StatusEnum.getEnumKey(business.getActStatus()));
		   }
//          if(erpReceipt.getActstatus()==2){
//			  String salesShop=erpReceipt.getSaleOrderId();
//			  List<CesOrderGoods> cesOrderGoods=cesOrderGoodsService.selectByMainId(salesShop);
//			  List<CesOrderCustomer> customerList =  cesOrderCustomerService.selectByMainId(salesShop);
//			  List<ErpSaleOutDetail> list = new ArrayList<>();
//			  int Num=0;
//			  BigDecimal totalAmount=new BigDecimal(0);
//			  for (CesOrderGoods card : cesOrderGoods){
//				  ErpSaleOutDetail sale=new ErpSaleOutDetail();
//
//				  sale.setGoodsId(card.getGoodId());
//				  sale.setOrderNum(card.getNum());
//				  Num=Num+card.getNum();
//				  sale.setTaxPrice(new BigDecimal(card.getPrice()));
//				  sale.setOriPrice(sale.getTaxPrice());
//				  sale.setTaxRate(new BigDecimal(17));
//				  sale.setDiscountRate(new BigDecimal(100));
//				  sale.setIsGift(0);
//				  sale.setSettleStatus(0);
//				  sale.setTotalPrice(new BigDecimal(card.getZongPrice()));
//				  totalAmount=totalAmount.add(sale.getTotalPrice());
//				  sale.setSaleOrderDetailId(card.getId());
//				  list.add(sale);
//			  }
//
//			  ErpDelivery erpSaleOut=new ErpDelivery();
//			  erpSaleOut.setCode(execute(null,null));
//			  erpSaleOut.setSettleStatus(0);
//			  erpSaleOut.setTotalNum(Num);
//			  erpSaleOut.setTotalGiftNum(0);
//			  erpSaleOut.setTotalAmount(totalAmount);
//			  erpSaleOut.setCustomerId(customerList.get(0)!=null?customerList.get(0).getCustomerid():null);
//			  erpSaleOut.setScId("1563050494330679298");
//			  erpSaleOut.setStatus(1);
//			  iErpDeliveryService.saveMain(erpSaleOut,list);
//		  }
		  if(erpReceipt.getActstatus()==2){
			  String salesShop=erpReceipt.getSaleOrderId();
			  List<CesOrderGoods> cesOrderGoods=cesOrderGoodsService.selectByMainId(salesShop);
			  List<CesOrderCustomer> customerList =  cesOrderCustomerService.selectByMainId(salesShop);
			  List<ErpDeliveryB> list = new ArrayList<>();
			  int Num=0;
			  BigDecimal totalAmount=new BigDecimal(0);
			  for (CesOrderGoods card : cesOrderGoods){
				  ErpDeliveryB sale=new ErpDeliveryB();

				  sale.setCmaterialid(card.getGoodId());
				  sale.setNastnum(card.getNum()+"");
				  Num=Num+card.getNum();

				  list.add(sale);
			  }

			  ErpDelivery erpSaleOut=new ErpDelivery();
			  erpSaleOut.setVbillcode(execute(null,null));
			  erpSaleOut.setActstatus(0);
			  erpSaleOut.setCsend(erpReceipt.getPersonId());
			  erpSaleOut.setDbilldate(new Date());
			  erpSaleOut.setCsenddeptvid("测试部门");
			  erpSaleOut.setNtotalastnum(Num+"");

			  iErpDeliveryService.saveMain(erpSaleOut,list);
		  }
             this.updateById(erpReceipt);

        }
	public String execute(JSONObject params, JSONObject formData) {
		String prefix = "CKD";
		//订单前缀默认为XSCK 如果规则参数不为空，则取自定义前缀
		if (params != null) {
			Object obj = params.get("prefix");
			if (obj != null) prefix = obj.toString();
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		int random = RandomUtils.nextInt(90) + 10;
		String value = prefix + format.format(new Date()) + random;
		// 根据formData的值的不同，生成不同的订单号
//		String name = formData.getString("name");
//		if (!StringUtils.isEmpty(name)) {
//			value += name;
//		}
		return value;
	}

   /**
     * 根据业务id返回业务表单数据<br/>
     * @param dataId
     * @return
     */
        @Override
        public Object getBusinessDataById(String dataId) {
            return this.getById(dataId);
        }
    /**
     * 返回当前节点的流程变量
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
            return null;
        }
    /**
     * 返回当前节点的候选人username
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
            // 通过当前节点来判断下一个节点的候选人并写回到反参中，如果为null，流程模块会根据默认设置处理

            return null;
        }


        @Override
        public void relationAct(String dataId) {
             //flowCommonService.initActBusiness("实验授课申请：dataId"+dataId,dataId,"erpReceiptService","process_tpho5a4q","process_tpho5a4q:4:32128f7c-ce77-11ec-843e-927841cf098b");
        }

}
